package site.zbox.tool.swing.table;

import java.awt.Color;
import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;

import site.zbox.tool.lang.Version;

@Version("2021.11.08")
public class ComponentTableCellRenderer implements TableCellRenderer {
    private final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();

    private static final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);

    private Border getCellNoFocusBorder() {
        final Border border = UIManager.getBorder("Table.cellNoFocusBorder");
        if (border == null) {
            return DEFAULT_NO_FOCUS_BORDER;
        }
        return border;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (value instanceof JComponent) {
            final JComponent component = (JComponent) value;

            if (isSelected) {
                component.setForeground(table.getSelectionForeground());
                component.setBackground(table.getSelectionBackground());
                component.setOpaque(true);
            } else {
                if (row % 2 == 0) {
                    component.setOpaque(false);
                } else {
                    component.setOpaque(true);
                }
                component.setBackground(table.getBackground());
                component.setForeground(table.getForeground());
            }

            if (hasFocus) {
                Border border = null;
                if (isSelected) {
                    border = UIManager.getBorder("Table.focusSelectedCellHighlightBorder");
                }
                if (border == null) {
                    border = UIManager.getBorder("Table.focusCellHighlightBorder");
                }
                component.setBorder(border);
                if (!isSelected && table.isCellEditable(row, column)) {
                    Color col;
                    col = UIManager.getColor("Table.focusCellForeground");
                    if (col != null) {
                        component.setForeground(col);
                    }
                    col = UIManager.getColor("Table.focusCellBackground");
                    if (col != null) {
                        component.setBackground(col);
                    }
                }
            } else {
                component.setBorder(getCellNoFocusBorder());
            }
            return component;
        }
        return renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }
}
